package cn.wolfcode.wms.service.impl;

import cn.wolfcode.wms.domain.Employee;
import cn.wolfcode.wms.mapper.EmployeeMapper;
import cn.wolfcode.wms.query.QueryObject;
import cn.wolfcode.wms.service.IEmployeeService;
import cn.wolfcode.wms.util.MD5;
import cn.wolfcode.wms.util.UserContext;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class EmployeeServiceImpl implements IEmployeeService {
    @Autowired
    private EmployeeMapper employeeMapper;
    public void save(Employee employee,Long[] ids) {
        String str = MD5.encode(employee.getPassword());
        employee.setPassword(str);
        employeeMapper.insert(employee);
        if (ids != null){
            for (Long id : ids) {
                employeeMapper.insertRealtion(employee.getId(),id);
            }
        }
    }

    public void update(Employee employee,Long[] ids) {
        employeeMapper.deleteRealtion(employee.getId());
        employeeMapper.updateByPrimaryKey(employee);
        if (ids != null){
            for (Long id : ids) {
                employeeMapper.insertRealtion(employee.getId(),id);
            }
        }
    }

    public void delete(Long id) {
        employeeMapper.deleteRealtion(id);
        employeeMapper.deleteByPrimaryKey(id);
    }

    public Employee get(Long id) {
        return employeeMapper.selectByPrimaryKey(id);
    }

    public List<Employee> list() {
        return employeeMapper.selectAll();
    }

    public PageInfo<Employee> query(QueryObject qo) {
//        调用分页包
        PageHelper.startPage(qo.getCurrentPage(),qo.getPageSize());
        List<Employee> list = employeeMapper.queryForList(qo);
        return new PageInfo<Employee>(list);
    }

    public void login(String username, String password) {
        String str = MD5.encode(password);
        Employee employee = employeeMapper.login(username, str);
        if (employee == null){
            throw new RuntimeException("账户与密码不一致");
        }else {
//            将登录用户存入session中,
            UserContext.setEmployee(employee);
            List<String> expressions = employeeMapper.selectExpressionByEmployeeId(employee.getId());
//            将权限存入session中,
            UserContext.setExpression(expressions);
        }
    }

}
